package com.dong.controller;

import com.dong.pojo.User;
import com.dong.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class UserController {

    @Autowired
    UserService userService;

    //到达登录界面
    @GetMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    //登录
    @RequestMapping("/login")
    public String login(String username, String password,String remember,String role,Model model){
        //1.获取Subject
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        //2.封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //3.执行登录的方法，只要没有异常就代表执行成功
        try {
            if("on".equals(remember)){
                token.setRememberMe(true);
            }
            session.setAttribute("role",role);
            session.setAttribute("username",username);
            subject.login(token);
            return "index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg","用户名不存在！");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }

    //注销
    @RequestMapping("/logout")
    public String logout(){
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        //注销
        subject.logout();

        return "login";
    }
}
